package com.ptszyxx.popose.module.main.mine;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.databinding.FragmentMineDiamondBinding;
import com.ptszyxx.popose.module.main.mine.adapter.MineCharmAdapter;
import com.ptszyxx.popose.module.main.mine.vm.MineDiamondVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.mine.CharmEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YRecyclerViewUtil;

import java.util.List;

public class MineDiamondFragment extends BaseFragment<FragmentMineDiamondBinding, MineDiamondVM> {

    private MineCharmAdapter adapter;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_mine_diamond;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MineDiamondVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MineDiamondVM.class);
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new MineCharmAdapter();
        YRecyclerViewUtil.init(getContext(), binding.recyclerView, adapter);

        binding.refreshLayout.setOnRefreshListener(o -> viewModel.requestDiamond(true));
        binding.refreshLayout.setOnLoadMoreListener(o -> viewModel.requestDiamond(false));
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestDiamond(true);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, new Observer<List<CharmEntity>>() {
            @Override
            public void onChanged(List<CharmEntity> list) {
                setAdapterUI(list);
            }
        });
    }

    private void setAdapterUI(List<CharmEntity> list) {
        binding.refreshLayout.finishRefresh();
        binding.refreshLayout.finishLoadMore();
        if (YCollectionUtil.isEmpty(list)){
            binding.refreshLayout.finishLoadMoreWithNoMoreData();
            if (viewModel.isRefresh()){
                binding.stateLayout.showEmpty();
            }
            return;
        }
        binding.stateLayout.showContent();

        if (viewModel.isRefresh()){
            adapter.setList(list);
        }else{
            adapter.addData(list);
        }
    }
}
